#include "Utilities/gl_utilities.h"
#include <QMouseEvent> 
#include <iostream>
#include <gl_window.h>
using namespace PhysLeo;

void GLwindow::initializeGL()
{
	if (glewInit() != GLEW_OK)
	{
		std::cout << "error: can't init glew!\n";
		std::exit(EXIT_FAILURE);
	}
	else {
		std::cout << "glew init successful" << std::endl;
	}
	glVerify(glClearColor(0.0, 0.2, 0.3, 1.0));
	glVerify(glShadeModel(GL_SMOOTH));
	glVerify(glEnable(GL_DEPTH_TEST));

	std::cout << "hahahaha" << std::endl;

    scene_graph_->initGlResourceGraph();
}

void GLwindow::paintGL()
{
	glClearColor(0.2f, 0.3f, 0.3f, 10.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    scene_graph_->drawGraph(dynamic_cast<CameraInterface&>(camera_));
}

void GLwindow::resizeGL(int w, int h)
{
	glViewport(0, 0, w, h);
	camera_.setAspect(float(w) / h);
}

void GLwindow::mousePressEvent(QMouseEvent * event)
{
	last_pos_ = event->pos();
}

void GLwindow::mouseMoveEvent(QMouseEvent * event)
{
	const auto pos = event->pos();
	const auto delta_pos = pos - last_pos_;
	last_pos_ = pos;
	auto scale = 0.02f;  //sensitivity of the mouse
	const auto camera_radius = glm::length(camera_.getFocusPosition() - camera_.getPosition());
	if (event->buttons() & Qt::LeftButton) {
		camera_.orbitLeft(delta_pos.x() *scale);
		camera_.orbitUp(delta_pos.y()*scale);
	}
	if (event->buttons() & Qt::MiddleButton) {
		camera_.zoomIn(camera_radius*delta_pos.y()*scale);
	}
	if (event->buttons() & Qt::RightButton) {
		scale *= 0.1f;
		camera_.translateLeft(camera_radius*delta_pos.x()*scale);
		camera_.translateUp(camera_radius*delta_pos.y()*scale);
	}
}

void GLwindow::wheelEvent(QWheelEvent * event)
{
	const auto scale = 0.02f;  //sensitivity of the mouse
	const auto camera_radius = glm::length(camera_.getFocusPosition() - camera_.getPosition());
	auto scroll = event->angleDelta();

	if (scroll.y() > 0)camera_.zoomOut(camera_radius*scale);
	else if (scroll.y() < 0)camera_.zoomIn(camera_radius*scale);

	last_pos_ = event->pos();
}
